import React from 'react'
import { message } from 'antd'
import { getType } from '@configs/convertType'
import UploadLimit from '@components/UploadLimit'
import JpgUpload from './JpgUpload'
import NormalUpload from './NormalUpload'
import { limit } from '@/configs/limit'
import './index.css'
import { getCount } from '../../utils/api'
import { openCountNotification } from '../../utils/countNotification'

const { maxCount } = limit

function Convert(props) {
  const [type, setType] = React.useState({
    name: '',
    description: '',
    accept: '',
    sourceType: '',
    exportType: '',
    downloadUrls: [],
  })
  const [overCount, setOverCount] = React.useState(null)
  // 获取目前的上传转换次数
  async function fetchCount(convertFlag) {
    const result = await getCount().then(
      (res) => {
        return res
      },
      (err) => {
        message.error('转换次数查询接口调用失败！')
        return maxCount
      }
    )
    // 是否超次数
    setOverCount(result >= maxCount)

    // 如果是转换时调用，就弹出转换次数提示
    if (convertFlag) {
      openCountNotification(result + 1)
    }
  }

  React.useEffect(() => {
    fetchCount()
    // 根据路由获取转换类型信息
    const { path } = props.match.params
    const type = getType(path)
    if (type === undefined) {
      props.history.push('/404')
      return
    }
    setType(type)
  }, [props.history, props.match.params])

  return (
    <div className='des-content'>
      <h1 className='transform-title'>{type['name']}</h1>
      <p className='transform-des'>
        {type['description']}
        {`（支持格式：${type['accept']}）`}
      </p>
      {/* 图片上传 */}
      {!overCount && type.sourceType === 'jpg' && <JpgUpload type={type} fetchCount={fetchCount} />}
      {/* 文件上传 */}
      {!overCount && type.sourceType !== 'jpg' && <NormalUpload type={type} fetchCount={fetchCount} />}
      {/* 超出限制 */}
      {overCount && <UploadLimit />}
    </div>
  )
}

export default Convert
